package org.bluesky.framework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.bluesky.framework.ResponseResult;
import org.bluesky.framework.dto.UpdateUserDto;
import org.bluesky.framework.dto.UserDto;
import org.bluesky.framework.entity.Role;
import org.bluesky.framework.entity.User;
import org.bluesky.framework.entity.UserRole;
import org.bluesky.framework.enums.AppHttpCodeEnum;
import org.bluesky.framework.exception.SystemException;
import org.bluesky.framework.mapper.UserMapper;
import org.bluesky.framework.service.RoleService;
import org.bluesky.framework.service.UserRoleService;
import org.bluesky.framework.service.UserService;
import org.bluesky.framework.utils.BeanCopyUtils;
import org.bluesky.framework.utils.SecurityUtils;
import org.bluesky.framework.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.beans.Transient;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户表(User)表服务实现类
 *
 * @author makejava
 * @since 2023-02-16 14:53:28
 */
@Service("UserService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleService roleService;
    @Override
    public ResponseResult userInfo() {
        //获取当前用户id
        Long userId = SecurityUtils.getUserId();
        //根据用户id查询用户信息
        User user = getById(userId);
        //封装UserInfoVo
        UserInfoVo vo = BeanCopyUtils.copyBean(user,UserInfoVo.class);
        return ResponseResult.okResult(vo);
    }

    @Override
    public ResponseResult updateUserInfo(User user) {
        updateById(user);
        return ResponseResult.okResult();
    }

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public ResponseResult registerUser(User user) {
        //对数据进行非空判断
        if(!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
        }
        //对数据进行是否存在的判断
        if(existUsername(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        //对密码进行加密
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        save(user);
        //存入数据库
        return ResponseResult.okResult();
    }

    private boolean existUsername(String userName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,userName);
        return count(queryWrapper) > 0;
    }

    @Override
    public PageVo getArticleList(UserDto userDto, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.hasText(userDto.getUserName())){
            queryWrapper.like(User::getUserName,userDto.getUserName());
        }
        if(StringUtils.hasText(userDto.getPhonenumber())){
            queryWrapper.eq(User::getPhonenumber,userDto.getPhonenumber());
        }
        if(StringUtils.hasText(userDto.getStatus())){
            queryWrapper.eq(User::getStatus,userDto.getStatus());
        }
        Page<User> page = new Page<>(pageNum,pageSize);
        page(page,queryWrapper);
        PageVo pageVo = new PageVo(page.getRecords(),page.getTotal());
        return pageVo;
    }

    @Override
    @Transient
    public ResponseResult addUser(UserRoleVo userRoleVo) {
        //对数据进行非空判断
        if(!StringUtils.hasText(userRoleVo.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if(!StringUtils.hasText(userRoleVo.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        if(!StringUtils.hasText(userRoleVo.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
        }
        if(!StringUtils.hasText(userRoleVo.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
        }
        //对数据进行是否存在的判断
        if(existUsername(userRoleVo.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        //对密码进行加密
        String encodePassword = passwordEncoder.encode(userRoleVo.getPassword());
        userRoleVo.setPassword(encodePassword);
        User user = BeanCopyUtils.copyBean(userRoleVo, User.class);
        //存入数据库
        save(user);
        List<Long> roleIds = userRoleVo.getRoleIds();
        List<UserRole> userRoles = roleIds.stream()
                .map(roleId -> new UserRole(user.getId(), roleId))
                .collect(Collectors.toList());
        userRoleService.saveBatch(userRoles);
        return ResponseResult.okResult();

    }

    @Override
    public ResponseResult getUser(Long id) {
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId,id);
        List<UserRole> userRoles = userRoleService.list(queryWrapper);
        List<Long> roleIds = userRoles.stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());
        List<Role> roles = roleService.list();
        User user = getById(id);
        UpdateUserVo updateUserVo = BeanCopyUtils.copyBean(user, UpdateUserVo.class);
        UUserVo uUserVo = new UUserVo(roleIds,roles,updateUserVo);
        return ResponseResult.okResult(uUserVo);
    }

    @Override
    @Transient
    public ResponseResult updateUser(UpdateUserDto userDto) {
        User user = BeanCopyUtils.copyBean(userDto,User.class);
        updateById(user);
        List<Long> roleIds = userDto.getRoleIds();
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId,user.getId());
        userRoleService.remove(queryWrapper);
        List<UserRole> userRoles = roleIds.stream()
                .map(roleId -> new UserRole(user.getId(), roleId))
                .collect(Collectors.toList());
        userRoleService.saveBatch(userRoles);
        return ResponseResult.okResult();
    }
}

